# -*- coding : utf-8 -*-

from PySide2.QtWidgets import QApplication, QMainWindow, QHeaderView, QMessageBox
from PySide2.QtCore import Qt, QThread, Signal

import sys
import time

from ui.ui_add_note import Ui_MainWindow


class MdiAddWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, session, parent=None):
        self.parent = None
        self.session = session
        super().__init__()
        self.task_post = None
        self.task_flag = True # 可以运行
        self.setupUi(self)
        self.pushButton_cancle.clicked.connect(self.cancle_widget_data)
        self.pushButton_submit.clicked.connect(self.submit_widget_data)
        
        
        
    def cancle_widget_data(self):
        self.lineEdit_title.setText("")
        self.textBrowser.setText("")
    
    def submit_widget_data(self):
        title = self.lineEdit_title.text()
        content = self.textBrowser.toPlainText()
        data_dict = {
            'title': title,
            'content': content,
        }
        if self.task_flag:
            self.task_post = PostData(self.session, data_dict)
            self.task_post.signal_done[str].connect(self.show_add_result)
            self.task_post.start()
            self.task_flag = False
        
    def show_add_result(self, string):
        if string == "ok":
            QMessageBox.information(self, '信息', '添加成功！', QMessageBox.Ok)
            self.cancle_widget_data()
        else:
            QMessageBox.information(self, '信息', '添加失败！', QMessageBox.Ok) 
        self.task_flag = True
    

# 提交数据
class PostData(QThread):
    
    signal_done = Signal(str)
    
    def __init__(self, session, data):
        super().__init__()
        self.session = session
        self.data = data
    
    def run(self):

        resp = None
        
        try:
            resp = self.session.requests.post(
                'http://127.0.0.1:8008/note/add/',
                cookies = self.session.session,
                data = self.data,
            )
        except Exception as e:
            self.signal_done.emit(str(e))
        else:
            content = resp.content
            
            if content is None or content.decode() == '添加成功':
                self.signal_done.emit('ok')
            else:
                self.signal_done.emit('error')


if __name__ == "__main__":
    # 开始运行
    import requests
    app = QApplication(sys.argv)
    winMain = MdiAddWindow(requests)
    winMain.show()
    # winMain.setMouseTracking(True) # 鼠标跟随
    app.exec_()